package com.powernobug.servlet;

import com.powernobug.bean.model.MarketAdmin;
import com.powernobug.bean.vo.BaseRespVo;
import com.powernobug.bean.vo.data.LoginData;
import com.powernobug.bean.vo.data.LoginInfoData;
import com.powernobug.service.AdminAuthService;
import com.powernobug.service.impl.AdminAuthServiceImpl;
import com.powernobug.util.Constant;
import com.powernobug.util.JsonUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 肖云戈
 * @CreateTime: 2024-08-20
 * @Description:
 */

@WebServlet("/auth/*")
public class AdminAuthServlet extends CommonServlet{
    private static AdminAuthService adminAuthService = new AdminAuthServiceImpl();

    public BaseRespVo login(HttpServletRequest req) throws IOException {
        // 获取请求体中的各项参数：username 和 password
        String jsonQuery = req.getReader().readLine();
        Map<String, String> map = null;
        try {map = JsonUtil.readJson(jsonQuery, Map.class);}
        catch (Exception e) {
            return BaseRespVo.errList(402);
        }

        String username = map.get("username");
        String password = map.get("password");

        // 采用select by username 的查找方式，判断password和数据库中查询到的password是否一致
        MarketAdmin marketAdmin = adminAuthService.login(username);
        // 不一致则告知用户：密码错误登陆失败（查询结果不为null）| 用户不存在登陆失败（查询结果为null）
        if (marketAdmin == null) {
            return BaseRespVo.errList(604);
        } else if (!marketAdmin.getPassword().equals(password)) {
            return BaseRespVo.errList(605);
        }

        // 一致则返回一个新的session，并封装为登录信息返回
        LoginData loginData = packageLoginData(req, marketAdmin);
        return BaseRespVo.okList(loginData);
    }

    public BaseRespVo info(HttpServletRequest req) {
        // 从请求行中解析出 token 信息（不必要）
//        String token = req.getParameter("token");
        // 在filter的过滤下，能被放行进入该servlet的请求只会是已登录的状态
        // 获取session，并获取其中的adminId值，以adminId作为查询的条件进行查询并封装返回
        HttpSession session = req.getSession();
        Integer adminId = (Integer) session.getAttribute(Constant.LOGIN_SESSION_KEY);
        LoginInfoData loginInfoData = adminAuthService.info(adminId);

        return BaseRespVo.okList(loginInfoData);
    }

    private static LoginData packageLoginData(HttpServletRequest req, MarketAdmin marketAdmin) {
        Map<String, String> adminInfo = new HashMap<>();
        adminInfo.put("nickName", marketAdmin.getUsername());
        adminInfo.put("avatar", marketAdmin.getAvatar());
        // 在调用 getSession，响应报文会自动添加一个请求头setCookie：JSESSION=xxxxx
        HttpSession session = req.getSession();
        session.setAttribute(Constant.LOGIN_SESSION_KEY, marketAdmin.getId());
        String token = session.getId();
        LoginData loginData = new LoginData(adminInfo, token);
        return loginData;
    }
}
